﻿
namespace Leetcode.N0224;
public class Solution
{
    public int Calculate(string s)
    {
        int index = 0;
        return this.Calculate(s, ref index);
    }

    private int Calculate(string s, ref int index)
    {
        int val = 0;
        var isAdd = true;
        for (; index < s.Length; index++)
        {
            switch (s[index])
            {
                case '+':
                    isAdd = true;
                    break;
                case '-':
                    isAdd = false;
                    break;
                case '(':
                    index++;
                    if (isAdd)
                    {
                        val += this.Calculate(s, ref index);
                    }
                    else
                    {
                        val -= this.Calculate(s, ref index);
                    }
                    break;
                case ')':
                    return val;
                case ' ':
                    break;
                default:
                    var val2 = this.ReadVal(s, ref index);
                    if (isAdd)
                    {
                        val += val2;
                    }
                    else
                    {
                        val -= val2;
                    }
                    break;
            }

        }
        return val;
    }
    private int ReadVal(string s, ref int index)
    {
        var val = s[index] - '0';
        while (index < s.Length - 1 && s[index + 1] >= '0' && s[index + 1] <= '9')
        {
            index++;
            val = val * 10 + s[index] - '0';
        }
        return val;
    }
}